package com.vitetest.api.service;

import com.vitetest.api.dto.LoginResponse;
import com.vitetest.api.entity.User;
import com.vitetest.api.repository.UserRepository;
import com.vitetest.api.util.JwtUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Optional;

/**
 * 用户服务类
 * 
 * @author ViteTest Team
 * @version 1.0.0
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class UserService {

    private final JwtUtil jwtUtil;
    private final PasswordEncoder passwordEncoder;
    private final UserRepository userRepository;

    /**
     * 用户认证
     */
    public LoginResponse authenticateUser(String username, String password) {
        log.info("用户登录尝试: {}", username);

        // 从数据库查找用户
        Optional<User> userOpt = userRepository.findByUsernameAndEnabled(username, true);
        if (!userOpt.isPresent()) {
            log.warn("用户不存在或已被禁用: {}", username);
            throw new RuntimeException("用户名或密码错误");
        }

        User user = userOpt.get();

        // 验证密码
        if (!passwordEncoder.matches(password, user.getPassword())) {
            log.warn("用户密码错误: {}", username);
            throw new RuntimeException("用户名或密码错误");
        }

        // 更新最后登录时间
        user.setLastLoginAt(LocalDateTime.now());
        userRepository.save(user);

        // 生成令牌
        String accessToken = jwtUtil.generateToken(username);
        String refreshToken = jwtUtil.generateRefreshToken(username);

        log.info("用户登录成功: {}", username);

        // 构建响应
        LoginResponse.UserInfo responseUserInfo = new LoginResponse.UserInfo(
                user.getUsername(),
                user.getEmail(),
                user.getAvatar(),
                user.getRole()
        );

        return new LoginResponse(
                accessToken,
                refreshToken,
                "Bearer",
                86400000L, // 24小时
                responseUserInfo
        );
    }

    /**
     * 刷新令牌
     */
    public LoginResponse refreshToken(String refreshToken) {
        try {
            String username = jwtUtil.getUsernameFromToken(refreshToken);
            if (!jwtUtil.validateToken(refreshToken)) {
                throw new RuntimeException("刷新令牌无效或已过期");
            }

            // 从数据库查找用户
            Optional<User> userOpt = userRepository.findByUsernameAndEnabled(username, true);
            if (!userOpt.isPresent()) {
                throw new RuntimeException("用户不存在或已被禁用");
            }

            User user = userOpt.get();

            // 生成新的令牌
            String newAccessToken = jwtUtil.generateToken(username);
            String newRefreshToken = jwtUtil.generateRefreshToken(username);

            LoginResponse.UserInfo responseUserInfo = new LoginResponse.UserInfo(
                    user.getUsername(),
                    user.getEmail(),
                    user.getAvatar(),
                    user.getRole()
            );

            return new LoginResponse(
                    newAccessToken,
                    newRefreshToken,
                    "Bearer",
                    86400000L,
                    responseUserInfo
            );
        } catch (Exception e) {
            log.error("刷新令牌失败: {}", e.getMessage());
            throw new RuntimeException("刷新令牌失败");
        }
    }
} 